/**
 Copyright (c) 2020-2022 宁波哥爱帮科技有限公司
 */
package cn.grab.fispservice.authentication.service.impl;

import cn.grab.fispapi.authentication.common.dtos.PageRequestDTO;
import cn.grab.fispapi.authentication.dto.EnterpriseAuthenticationDTO;
import cn.grab.fispapi.authentication.dto.PersonalAuthenticationDTO;
import cn.grab.fispapi.authentication.dto.SysUserAuthenticationDTO;
import cn.grab.fispapi.authentication.vo.EnterpriseAuthenticationVO;
import cn.grab.fispapi.authentication.vo.PersonalAuthenticationVO;
import cn.grab.fispapi.authentication.vo.SysUserAuthenticationVO;
import cn.grab.fispapi.upms.dto.SysAddRoleDTO;
import cn.grab.fispapi.upms.vo.SysFindRoleVO;
import cn.grab.fispapi.upms.vo.SysRoleVO;
import cn.grab.fispservice.authentication.mapper.EnterpriseAuthenticationMapper;
import cn.grab.fispservice.authentication.mapper.PersonalAuthenticationMapper;
import cn.grab.fispservice.authentication.mapper.UserAuthenticationMapper;
import cn.grab.fispservice.authentication.model.EnterpriseAuthentication;
import cn.grab.fispservice.authentication.model.PersonalAuthentication;
import cn.grab.fispservice.authentication.model.UserAuthentication;
import cn.grab.fispservice.authentication.model.common.ToExamine;
import cn.grab.fispservice.authentication.service.UserAuthenticationService;
import cn.grab.fispservice.upms.mapper.SysRoleMapper;
import cn.grab.fispservice.upms.mapper.SysUserMapper;
import cn.grab.fispservice.upms.mapper.SysUserRoleMapper;
import cn.grab.fispservice.upms.model.SysRole;
import cn.grab.fispservice.upms.model.SysUser;
import cn.grab.fispservice.upms.model.SysUserRole;
import cn.grab.fispservice.upms.service.SysRoleService;
import cn.grab.fispservice.upms.service.SysUserService;
import cn.grab.fispservice.util.ThreadLocalUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fontana.base.result.Result;
import com.fontana.base.result.ResultCode;
import com.fontana.db.mapper.BaseDaoMapper;
import com.fontana.db.service.impl.AbstractBaseService;
import com.fontana.oss.model.ObjectInfo;
import com.fontana.oss.service.IOssService;
import com.fontana.util.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description 用户认证关联服务类实现类
 * @author 16411
 * @date 2022/12/14 15:38
 */
@Service
public class UserAuthenticationServiceImpl extends AbstractBaseService<UserAuthentication,Long> implements UserAuthenticationService {

  @Resource
  private UserAuthenticationMapper userAuthenticationMapper;

  @Resource
  private SysRoleService sysRoleService;

  @Resource
  private SysRoleMapper sysRoleMapper;

  @Resource
  private SysUserRoleMapper sysUserRoleMapper;

  @Resource
  private SysUserMapper sysUserMapper;

  @Resource
  private PersonalAuthenticationMapper personalAuthenticationMapper;

  @Resource
  private EnterpriseAuthenticationMapper enterpriseAuthenticationMapper;

  @Resource
  private IOssService iOssService;

  @Override
  protected BaseDaoMapper<UserAuthentication> mapper() {
    return userAuthenticationMapper;
  }

  /**
   *@Param:
   *@return: 返回用户列表
   *@Author: xxxx
   *@date: 2022/12/26
   */
  @Override
  public Result<Object> findIsAuthentication(SysUserAuthenticationDTO sysUserAuthenticationDTO) {

/*
    //校验参数拼接查询参数,用户名
    LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
    if (sysUserAuthenticationDTO.getUserName() != null){
      queryWrapper.like(SysUser::getLoginName,sysUserAuthenticationDTO.getUserName());
    }

    //创建page分页对象
    Page<SysUser> objectPage = new Page<>(sysUserAuthenticationDTO.getPage(),sysUserAuthenticationDTO.getSize());

    //根据用户名模糊查询数据库,当queryWrapper为空,查询所有
    Page<SysUser> sysUserPage = sysUserMapper.selectPage(objectPage, queryWrapper);

    //获取用户列表,获取所有用户id
    List<SysUser> records = sysUserPage.getRecords();
    List<Long> userList = records.stream().map(SysUser::getUserId).collect(Collectors.toList());
*/
    //校验分页参数
    sysUserAuthenticationDTO.checkParam();

    //设置分页参数
    Integer page = sysUserAuthenticationDTO.getPage();
    Integer size = sysUserAuthenticationDTO.getSize();


    page= (page - 1) * size;

    sysUserAuthenticationDTO.setPage(page);

    //根据用户id查询认证中间关联表信息
     List<SysUserAuthenticationVO> list = userAuthenticationMapper.findUserAuthenticationList(sysUserAuthenticationDTO);



    return Result.failed(list,ResultCode.SUCCESS);
  }



  /**
   *@Param: SysAddRoleDTO 用户选择角色列表id, PersonalAuthenticationDTO 用户个人认证信息 ,EnterpriseAuthenticationDTO 用户企业认证信息
   *@return: 认证应答消息
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @Override
  @Transactional
  public Result<Object> addUserAuthentication(SysAddRoleDTO sysAddRoleDTO,
      PersonalAuthenticationDTO personalAuthenticationDTO,
      EnterpriseAuthenticationDTO enterpriseAuthenticationDTO,
      MultipartFile imageFile) {

    //获取当前登录的用户的userId,
    Long userId = ThreadLocalUtils.get();


    //将用户角色信息添加到角色表中
    Result<Object> objectResult = sysRoleService.addSysUserRole(sysAddRoleDTO);
    if (!objectResult.isSuccess()){
      return Result.failed(ResultCode.FAIL,"角色选择冲突,请检查后重试");
    }

    //根据当前用户的userId查询用户认证关联表信息
    UserAuthentication userAuthentication = userAuthenticationMapper.selectById(userId);

    //校验当前认证关联表中是否为空
    if (userAuthentication == null){

      //当查询的关联表中的数据为null
      //添加当前用认证的个人信息,拷贝并创建个人认证实体类对象
      PersonalAuthentication personalAuthentication = BeanUtil.copy(personalAuthenticationDTO,
          PersonalAuthentication.class);

      //封装个人认证表当前的对象
      personalAuthentication.setCreatedUserId(userId);
      personalAuthentication.setCreatedTime(new Date());
      personalAuthentication.setUpdatedUserId(userId);
      personalAuthentication.setUpdatedTime(new Date());
      personalAuthentication.setWhetherExamine(0);

      //存储个人认证信息
      personalAuthenticationMapper.insert(personalAuthentication);


      //添加当前用户企业认证信息,拷贝并创建企业认证信息
      EnterpriseAuthentication enterpriseAuthentication = BeanUtil.copy(enterpriseAuthenticationDTO,
          EnterpriseAuthentication.class);

      //上传用户上传的营业执照url
      ObjectInfo info = iOssService.upload(imageFile);
      String objectUrl = info.getObjectUrl(); //上传文件查看路径
      String objectPath = info.getObjectPath(); //上传文件保存路径

     // String objectUrl ="https://image.baidu.com/search/detail?tn=baiduimagedetail&word=%E5%9F%8E%E5%B8%82%E5%BB%BA%E7%AD%91%E6%91%84%E5%BD%B1%E4%B8%93%E9%A2%98&album_tab=%E5%BB%BA%E7%AD%91&album_id=7&ie=utf-8&fr=albumsdetail&cs=1595072465,3644073269&pi=3977&pn=0&ic=0&objurl=https%3A%2F%2Ft7.baidu.com%2Fit%2Fu%3D1595072465%2C3644073269%26fm%3D193%26f%3DGIF"; //上传文件查看路径
    //  String objectPath = "https://image.baidu.com/search/detail?tn=baiduimagedetail&word=%E5%9F%8E%E5%B8%82%E5%BB%BA%E7%AD%91%E6%91%84%E5%BD%B1%E4%B8%93%E9%A2%98&album_tab=%E5%BB%BA%E7%AD%91&album_id=7&ie=utf-8&fr=albumsdetail&cs=1595072465,3644073269&pi=3977&pn=0&ic=0&objurl=https%3A%2F%2Ft7.baidu.com%2Fit%2Fu%3D1595072465%2C3644073269%26fm%3D193%26f%3DGIF";
      //封装企业认证信息对象
      enterpriseAuthentication.setBusinessSeeLicense(objectUrl);
      enterpriseAuthentication.setBusinessStorageLicense(objectPath);
      enterpriseAuthentication.setWhetherExamine(0);
      enterpriseAuthentication.setCreatedUserId(userId);
      enterpriseAuthentication.setCreatedTime(new Date());
      enterpriseAuthentication.setUpdatedUserId(userId);
      enterpriseAuthentication.setUpdatedTime(new Date());


      //保存进数据库
      enterpriseAuthenticationMapper.insert(enterpriseAuthentication);

      //获取存储的个人认证和企业认证id
      Long personalAuthenticationId = personalAuthentication.getId();
      Long enterpriseAuthenticationId = enterpriseAuthentication.getId();

      //创建关联表对象,封装对象
       userAuthentication = new UserAuthentication();
       userAuthentication.setUserId(userId);
       userAuthentication.setPersonalAuthenticationId(personalAuthenticationId);
       userAuthentication.setEnterpriseAuthenticationId(enterpriseAuthenticationId);
       userAuthentication.setAuthenticationType(0);

       //存储进中间表
      userAuthenticationMapper.insert(userAuthentication);
    } else {

      //当中间表信息不为空
      //根据当前中间表信息查询个人认证和企业认证信息
      PersonalAuthentication personalAuthentication = personalAuthenticationMapper.selectById(
          userAuthentication.getPersonalAuthenticationId());

      //将拷贝对象替换内容
      BeanUtil.copyProperties(personalAuthenticationDTO,personalAuthentication);

      //封装对象
      personalAuthentication.setUpdatedTime(new Date());
      personalAuthentication.setUpdatedUserId(userId);
      personalAuthentication.setWhetherExamine(0);

      //修改数据库表信息
      personalAuthenticationMapper.updateById(personalAuthentication);

      //查询企业认证信息
      EnterpriseAuthentication enterpriseAuthentication = enterpriseAuthenticationMapper.selectById(
          userAuthentication.getEnterpriseAuthenticationId());

      //替换企业认证信息内容
      BeanUtil.copyProperties(enterpriseAuthenticationDTO,enterpriseAuthentication);

      //删除之前用户保存的企业营业执照信息
      iOssService.delete(enterpriseAuthentication.getBusinessStorageLicense());

      //重新上传企业营业执照
      ObjectInfo info = iOssService.upload(imageFile);
      String objectUrl = info.getObjectUrl();
      String objectPath = info.getObjectPath();
     //   String objectUrl = "https://image.baidu.com/search/detail?tn=baiduimagedetail&word=%E5%9F%8E%E5%B8%82%E5%BB%BA%E7%AD%91%E6%91%84%E5%BD%B1%E4%B8%93%E9%A2%98&album_tab=%E5%BB%BA%E7%AD%91&album_id=7&ie=utf-8&fr=albumsdetail&cs=2511982910,2454873241&pi=3982&pn=5&ic=0&objurl=https%3A%2F%2Ft7.baidu.com%2Fit%2Fu%3D2511982910%2C2454873241%26fm%3D193%26f%3DGIF";
     // String objectPath = "https://image.baidu.com/search/detail?tn=baiduimagedetail&word=%E5%9F%8E%E5%B8%82%E5%BB%BA%E7%AD%91%E6%91%84%E5%BD%B1%E4%B8%93%E9%A2%98&album_tab=%E5%BB%BA%E7%AD%91&album_id=7&ie=utf-8&fr=albumsdetail&cs=2511982910,2454873241&pi=3982&pn=5&ic=0&objurl=https%3A%2F%2Ft7.baidu.com%2Fit%2Fu%3D2511982910%2C2454873241%26fm%3D193%26f%3DGIF";
      //封装企业信息对象
      enterpriseAuthentication.setBusinessSeeLicense(objectUrl);
      enterpriseAuthentication.setBusinessStorageLicense(objectPath);
      enterpriseAuthentication.setUpdatedUserId(userId);
      enterpriseAuthentication.setUpdatedTime(new Date());
      enterpriseAuthentication.setWhetherExamine(0);

      //修改数据库中企业认证信息
     enterpriseAuthenticationMapper.updateById(enterpriseAuthentication);

     //修改审核状态为未审核
     userAuthentication.setAuthenticationType(0);
     userAuthenticationMapper.updateById(userAuthentication);
    }

    return Result.failed(ResultCode.SUCCESS,"认证信息已提交,请等待管理员审核!");
  }



  /**
   *@Param: 用户认证数据回显
   *@return: Map 结果集
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @Override
  public Result<Object> findUserAuthentication() {

    //获取当前登录的用户id
    Long userId = ThreadLocalUtils.get();

    //根据userid查询当前用户选择的角色信息
    List<SysRoleVO> sysRoleVOList = sysRoleService.getSysRoleVOList();

    //根据当前userId查询用户认证中间表关联信息
    UserAuthentication userAuthentication = userAuthenticationMapper.selectById(userId);

    //校验中间表信息,用户是否已经进行认证
    if (userAuthentication == null){
      return Result.failed(ResultCode.SUCCESS,"用户还未进行认证");
    }

    //创建结果集
    Map<String, Object> map = new HashMap<>();

    //校验认证信息
    if (userAuthentication.getAuthenticationType() == 2){
       return Result.failed(ResultCode.FAIL,"审核失败,请检查后重试!");
    } else if (userAuthentication.getAuthenticationType() == 1){
      return Result.failed(ResultCode.SUCCESS,"正在审核中,如情况紧急请联系管理员处理");
    }

    //获取用户个人认证信息
    PersonalAuthentication personalAuthentication = personalAuthenticationMapper.selectById(
        userAuthentication.getPersonalAuthenticationId());

    //创建并拷贝对象到用户个人认证视图实体类
    PersonalAuthenticationVO personalAuthenticationVO = BeanUtil.copy(personalAuthentication,
        PersonalAuthenticationVO.class);

    //获取用户企业认证信息
    EnterpriseAuthentication enterpriseAuthentication = enterpriseAuthenticationMapper.selectById(
        userAuthentication.getEnterpriseAuthenticationId());

    //创建并拷贝对象到用户企业认证视图实体类
    EnterpriseAuthenticationVO enterpriseAuthenticationVO = BeanUtil.copy(enterpriseAuthentication,
        EnterpriseAuthenticationVO.class);

    //封装结果集
    map.put("personalAuthenticationVO",personalAuthenticationVO);
    map.put("enterpriseAuthenticationVO",enterpriseAuthenticationVO);
    map.put("sysRoleVOList",sysRoleVOList);

    return Result.failed(map,ResultCode.SUCCESS);
  }

  /**
   *@Param: 用户认证审核
   *@return: 审核结果应答信息
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @Override
  public Result<Object> toExamineAuthentication(Long userId , Integer status) {

   //根据用户id查询当前认证信息
    UserAuthentication userAuthentication = userAuthenticationMapper.selectById(userId);


    //校验参数,是否审核通过 ,0代表审核失败 ,1代表审核成功
    if (status == 0){
        //审核失败,修改审核状态

      //修改当前审核状态为未通过
      userAuthentication.setAuthenticationType(ToExamine.ToExamineFAIL);
      userAuthenticationMapper.updateById(userAuthentication);

    } else if(status ==1){
      //审核状态为1,修改审核状态为通过
      userAuthentication.setAuthenticationType(ToExamine.ToExamineSUCCESS);
      userAuthenticationMapper.updateById(userAuthentication);

    }
    return Result.failed(ResultCode.SUCCESS,"审核成功");
  }



  /**
   用户认证审核,展示认证详细信息接口
   *@Param:  userId
   *@return: 用户认证详细信息
   *@Author: xxxx
   *@date: 2022/12/28
   */
  @Override
  public Result<Object> findUserAuthenticationOne(Long userId) {
    //根据用户id,查询当前认证信息
    UserAuthentication userAuthentication = userAuthenticationMapper.selectById(userId);

    //校验当前用户是否进行了认证信息
    if (userAuthentication == null){
      return Result.failed(ResultCode.FAIL,"当前用户未进行认证");
    }

    //根据用户id查询当前用户的选择的角色信息
    List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(
        Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));

    List<Long> accountRoleIds =  sysUserRoles.stream().map(SysUserRole::getRoleId)
        .collect(Collectors.toList());

    //根据角色id,查询角色信息
    /*LambdaQueryWrapper<SysRole> eq = new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleId,
        accountRoleIds);*/
    List<SysRole> sysRoleList = sysRoleMapper.selectBatchIds(accountRoleIds);
    List<SysRoleVO> accountRole = new ArrayList<>();
    for (SysRole sysRole : sysRoleList) {
      SysRoleVO sysRoleVO = new SysRoleVO();
      sysRoleVO.setRoleId(sysRole.getRoleId());
      sysRoleVO.setRoleName(sysRole.getRoleName());

      accountRole.add(sysRoleVO);
    }

    //查询当前的默认角色信息
    SysUser sysUser = sysUserMapper.selectById(userId);
    Long defaultRoleId = sysUser.getDefaultRole();

    SysRole sysRole = sysRoleMapper.selectById(defaultRoleId);
    SysRoleVO defaultRole = new SysRoleVO();
    defaultRole.setRoleId(sysRole.getRoleId());
    defaultRole.setRoleName(sysRole.getRoleName());

    //封装视图实体类
    SysFindRoleVO sysFindRoleVO = new SysFindRoleVO();
    sysFindRoleVO.setAccountRole(accountRole);
    sysFindRoleVO.setDefaultRole(defaultRole);


    //查询当前用户的个人认证信息
    PersonalAuthentication personalAuthentication = personalAuthenticationMapper.selectById(
        userAuthentication.getPersonalAuthenticationId());


    //查询当前用户的企业认证信息
    EnterpriseAuthentication enterpriseAuthentication = enterpriseAuthenticationMapper.selectById(
        userAuthentication.getEnterpriseAuthenticationId());

    //创建结果集
    Map<String, Object> map = new HashMap<>();
    map.put("sysFindRoleVO",sysFindRoleVO);
    map.put("personalAuthentication",personalAuthentication);
    map.put("enterpriseAuthentication",enterpriseAuthentication);


   //返回结果集
    return Result.failed(map,ResultCode.SUCCESS);
  }
}
